﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;

namespace VPLink2013.Webpart
{
    public class VosOutils : WebpartVPLink
    {
        private bool isVplinkRoot = false;
        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = string.Empty;
            ContextTrace.PrefixFileName = "webpart VosOutils";
            if (!string.IsNullOrEmpty(siteUrl) && !string.IsNullOrEmpty(ParamSharepointSite))
            {
                Uri siteUri = new Uri(siteUrl);
                Uri paramSiteUrl = new Uri(ParamSharepointSite);
                if (Uri.Compare(paramSiteUrl, siteUri, UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped, StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    isVplinkRoot = true;
                }
            }

            UtilisateurCrt = new Utilisateur();
            UtilisateurCrt.Login = this.Context.User.Identity.Name;

            try
            {
                SPSecurity.RunWithElevatedPrivileges
                (delegate()
                {
                    strFileCacheUtilisateur = pathCache + @"\MenuGeneralUtilisateur\MenuGeneral_"
                        + StringAfter(this.Context.User.Identity.Name) + ".xml";
                    SetUtilisateurCrt();
                    // Comment to test
                    //if (UtilisateurCrt.IsInterne == "1")
                    //{
                    if (!isVplinkRoot)
                        {
                            //VP Voyage
                            string strHtmlFileCache = pathCache + @"\VosOutils\VosOutils_"
                                    + "Interne" + UtilisateurCrt.IsInterne + "_Ecommerce" + UtilisateurCrt.IsEcommerce + "_ProductionVoyage" + UtilisateurCrt.IsProductionVoyage + "_CommercialVoyage" + UtilisateurCrt.IsCommercialVoyage + ".htm";

                            strHtml = GetVosOutilsData(strHtml, strHtmlFileCache);
                        }
                        else
                        {
                            string strHtmlFileCache = pathCache + @"\VosOutils\VosOutils_"
                                + "Interne" + UtilisateurCrt.IsInterne + "_Manager" + UtilisateurCrt.IsManager + ".htm";

                            strHtml = GetVosOutilsData(strHtml, strHtmlFileCache);
                        }
                    //}
                });
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            return strHtml;
        }

        private string GetVosOutilsData(string strHtml, string strHtmlFileCache)
        {
            FileSerialization.CheckFileCacheExists(strHtmlFileCache, 30);

            if (System.IO.File.Exists(strHtmlFileCache))
            {
                strHtml = System.IO.File.ReadAllText(strHtmlFileCache);
                ContextTrace.AddTrace("File cache found !");
            }
            else
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        SPList lst = web.Lists.TryGetList(ListTitles.VosOutilsTitle);
                        if (lst != null)
                        {
                            strHtml = ProcessVosOutils(lst);
                            TraceFile(strHtmlFileCache, strHtml);
                        }
                    }
                }
            }
            return strHtml;
        }
        #endregion get HTML

        private string ProcessVosOutils(SPList lst)
        {
            SPQuery spQuery = new SPQuery();
            StringBuilder sb = new StringBuilder();
            sb.Append("<Where>");
            sb.Append("<Eq><FieldRef Name='Visible'/><Value Type='Text'>Oui</Value></Eq>");
            sb.Append("</Where>");
            sb.Append("<OrderBy><FieldRef Name='Ordre' Ascending='TRUE'/><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>");
            string Query = sb.ToString();
            spQuery.Query = Query;
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);

            SPListItemCollection items = lst.GetItems(spQuery);
            int intWidth = 100 / items.Count;

            sbHtml.AppendLine("<div class=\"bloc_right-column\">");

            if (isVplinkRoot)
            {
                sbHtml.AppendLine("<h1>VOS OUTILS RH</h1>");
            }
            else
            {
                sbHtml.AppendLine("<h1>VOS OUTILS <span style=\"float: right;font-size: 10px;font-weight: normal;\"><a href=\"" + ParamSharepointSite + "/Lists/Vos%20outils/AllItems.aspx\">voir la liste</a></span></h1>");
            }
            sbHtml.AppendLine("<div id=\"tools_rh\">");
            sbHtml.AppendLine("<ul>");
            bool flagCommercial = false;
            bool flagProduction = false;
            bool flagEcommerce = false;
            foreach (SPListItem item in items)
            {
                if (!isVplinkRoot)
                {
                    //vp voyage
                    flagCommercial = false;
                    flagProduction = false;
                    flagEcommerce = false;
                    string strCommercial = VPLink2013SPHelper.GetValue(item, "Commercial");
                    if (strCommercial == "Oui" && UtilisateurCrt.IsCommercialVoyage == "1")
                    {
                        flagCommercial = true;
                    }

                    string strProduction = VPLink2013SPHelper.GetValue(item, "Production");
                    if (strProduction == "Oui" && UtilisateurCrt.IsProductionVoyage == "1")
                    {
                        flagProduction = true;
                    }

                    string strEcommerce = VPLink2013SPHelper.GetValue(item, "Ecommerce");
                    if (strEcommerce == "Oui" && UtilisateurCrt.IsEcommerce == "1")
                    {
                        flagEcommerce = true;
                    }


                    if (!flagCommercial && !flagProduction && !flagEcommerce)
                    {
                        continue;
                    }
                }
                else
                {
                    ContextTrace.AddTrace("-------------------------------");
                    string strSeulementManagers = VPLink2013SPHelper.GetValue(item, "Seulement managers");
                    if (strSeulementManagers == "Oui" && UtilisateurCrt.IsManager != "1")
                    {
                        ContextTrace.AddTrace("Lien non affiché car utilisateur courant non manager");
                        continue;
                    }

                    string strSeulementInterimManagers = VPLink2013SPHelper.GetValue(item, "Seulement Managers des Interims");
                    if (strSeulementInterimManagers == "Oui" && UtilisateurCrt.IsInterimManager != "1")
                    {
                        ContextTrace.AddTrace("Lien non affiché car utilisateur courant non manager des interims");
                        continue;
                    }

                    string strSeulementInternes = VPLink2013SPHelper.GetValue(item, "Seulement internes");
                    if (strSeulementInternes == "Oui" && UtilisateurCrt.IsInterne != "1")
                    {
                        ContextTrace.AddTrace("Lien non affiché car utilisateur courant non interne");
                        continue;
                    }
                }


                string strURL = VPLink2013SPHelper.GetValue(item, "URL");
                string strTexteURL = HttpUtility.HtmlEncode(GetValueAfterSeparator(strURL));
                string strLinkURL = GetValueBeforeSeparator(strURL);
                ContextTrace.AddTrace("strURL : " + strURL);
                ContextTrace.AddTrace("strTexteURL : " + strTexteURL);
                ContextTrace.AddTrace("strLinkURL : " + strLinkURL);

                string strEnSavoirPlus = VPLink2013SPHelper.GetValue(item, "En savoir plus");
                string strLinkEnSavoirPlus = GetValueBeforeSeparator(strEnSavoirPlus);
                string strTexteEnSavoirPlus = GetValueAfterSeparator(strEnSavoirPlus);
                ContextTrace.AddTrace("strEnSavoirPlus : " + strEnSavoirPlus);
                ContextTrace.AddTrace("strLinkEnSavoirPlus : " + strLinkEnSavoirPlus);
                ContextTrace.AddTrace("strTexteEnSavoirPlus : " + strTexteEnSavoirPlus);
                ContextTrace.AddTrace("strEnSavoirPlus : " + strEnSavoirPlus);

                sbHtml.Append("<li>");
                sbHtml.AppendLine("<img src=\"/_LAYOUTS/15/VPLink2013/images/li-arrow.png\">");
                string titrePiwik = strTexteURL.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                sbHtml.Append("<a class=\"name_tools\" href=\"" + strLinkURL + "\" onclick=\"javascript:_paq.push(['trackPageView', 'VOS OUTILS RH/" + titrePiwik + "']);\" target=\"_blank\">" + strTexteURL + "</a>");
                if (!string.IsNullOrEmpty(strLinkEnSavoirPlus))
                    sbHtml.Append("<a class=\"more_tools\" href=\"" + strLinkEnSavoirPlus + "\" onclick=\"javascript:_paq.push(['trackPageView', 'VOS OUTILS RH/" + titrePiwik + "/En savoir plus']);\">En savoir plus</a>");
                sbHtml.AppendLine("</li>");
            }
            sbHtml.AppendLine("</ul>");
            sbHtml.AppendLine("</div>");
            sbHtml.AppendLine("</div>");

            return sbHtml.ToString();
        }
    }
}
